﻿using System.Collections.Generic;
using System.Linq;
using CID.Domain.Exceptions;
using NailsFramework.Persistence;

namespace CID.Domain.Users
{
    public class User : Model<User>, IUser
    {
        public virtual int Id { get; private set; }
        public virtual string Name { get; set; }
        public virtual string UserName { get; set; }
        public virtual string Email { get; set; }
        public virtual bool Enabled { get; set; }

        private IList<IUserRoleAssignment> assignedRoles = new List<IUserRoleAssignment>();
        public virtual IEnumerable<IUserRoleAssignment> AssignedRoles { get { return assignedRoles; } }

        protected User()
        {
        }

        public User(string name, string userName, string email) : this()
        {
            Name = name;
            UserName = userName;
            Email = email;
            Enabled = true;
        }

        public virtual void AssignRole(UserRole userRole)
        {
            if (!Enabled) throw new InvalidActionForDisabledObjectException("assign a role", typeof(User));

            var userRoleAssignment = AssignedRoles.FirstOrDefault(x => x.UserRole.Equals(userRole));
            if (userRoleAssignment == null)
                assignedRoles.Add(new UserRoleAssignment(this, userRole));
        }

        public virtual void UnassignRole(UserRole userRole)
        {
            if (!Enabled) throw new InvalidActionForDisabledObjectException("unassign a role", typeof(User));

            var userRoleAssignment = AssignedRoles.FirstOrDefault(x => x.UserRole.Equals(userRole));
            if (userRoleAssignment != null)
                assignedRoles.Remove(userRoleAssignment);
        }

        public virtual bool Is(UserRole userRole)
        {
            return AssignedRoles.Count(x => x.UserRole.Equals(userRole)) > 0;
        }
    }
}
